package com.dk.goodnight.controller;

import com.alibaba.fastjson.JSONObject;
import com.dk.goodnight.api.EmptyBean;
import com.dk.goodnight.api.ErrorCodeEnum;
import com.dk.goodnight.api.Result;
import com.dk.goodnight.model.TokenBean;
import com.dk.goodnight.model.UserBean;
import com.dk.goodnight.model.UserInfoBean;
import com.dk.goodnight.model.UserLoginSuccessBean;
import com.dk.goodnight.service.UserServiceImpl;
import com.dk.goodnight.utils.JWTToken;
import com.dk.goodnight.utils.StringUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserServiceImpl userService;


    @PostMapping("/doRegister")
    @ResponseBody
    public String userRegister(@RequestParam(value = "phone_number") String phoneNumber, @RequestParam(value = "password") String password) {
        UserBean userBean = userService.getUserByPhone(phoneNumber);
        //用户表中不存在此手机号,添加用户
        if (userBean == null) {
            //密码进行md5加密
            String user_password = DigestUtils.md5DigestAsHex(password.getBytes());

            UserBean userBeanInsert = new UserBean();
            userBeanInsert.setUser_phone(phoneNumber);
            userBeanInsert.setUser_password(user_password);
            int userId = userService.register(userBeanInsert);
            //用户信息写入成功
            if (userId > 0) {
                //生成token，向token表中写入token

                String token = JWTToken.createToken(userId);
                TokenBean tokenBean = new TokenBean();
                tokenBean.setUser_id(userId);
                tokenBean.setToken(token);
                int tokenId = userService.insertToken(tokenBean);

                //token插入成功
                if (tokenId > 0) {
                    UserLoginSuccessBean userLoginSuccessBean = new UserLoginSuccessBean();
                    userLoginSuccessBean.setToken(token);
                    Result<UserLoginSuccessBean> result = new Result<>(userLoginSuccessBean);
                    return JSONObject.toJSONString(result);

                    //用户注册成功，token插入失败，让用户登录
                } else {
                    EmptyBean emptyBean = new EmptyBean();
                    Result<EmptyBean> result = new Result<>(emptyBean, ErrorCodeEnum.FAIL, "注册成功，请进行登录");
                    return JSONObject.toJSONString(result);
                }

            } else {
                EmptyBean emptyBean = new EmptyBean();
                Result<EmptyBean> result = new Result<>(emptyBean, ErrorCodeEnum.FAIL, "用户注册信息写入失败");
                return JSONObject.toJSONString(result);
            }

            //用户已经是平台用户
        } else {
            EmptyBean emptyBean = new EmptyBean();
            Result<EmptyBean> result = new Result<>(emptyBean, ErrorCodeEnum.FAIL, "手机号已经存在，请进行登录");
            return JSONObject.toJSONString(result);
        }
    }


    /**
     * 使用手机号验证码登录
     */
    @PostMapping("/doLogin")
    @ResponseBody
    public String deLogin(@RequestParam(value = "phone_number") String phoneNumber, @RequestParam(value = "password") String password) {
        if (StringUtils.isEmpty(phoneNumber) || StringUtils.isEmpty(password)) {
            EmptyBean emptyBean = new EmptyBean();
            Result<EmptyBean> result = new Result<>(emptyBean, ErrorCodeEnum.FAIL, "请填写登录信息");
            return JSONObject.toJSONString(result);
        }

        UserBean userBean = userService.getUserByPhone(phoneNumber);

        //用户表中不存在此手机号
        if (userBean == null) {
            EmptyBean emptyBean = new EmptyBean();
            Result<EmptyBean> result = new Result<>(emptyBean, ErrorCodeEnum.FAIL, "用户不存在");
            return JSONObject.toJSONString(result);

            //用户已经是平台用户
        } else {
            //密码进行md5加密
            String user_password = DigestUtils.md5DigestAsHex(password.getBytes());
            //密码一致
            if (user_password.equals(userBean.getUser_password())) {
                //用户信息写入成功
                if (userBean.getUser_id() > 0) {
                    //生成token，向token表中写入token

                    String token = JWTToken.createToken(userBean.getUser_id());
                    TokenBean tokenBean = new TokenBean();
                    tokenBean.setUser_id(userBean.getUser_id());
                    tokenBean.setToken(token);
                    int tokenId = userService.insertToken(tokenBean);

                    //token插入成功
                    if (tokenId > 0) {
                        UserLoginSuccessBean userLoginSuccessBean = new UserLoginSuccessBean();
                        userLoginSuccessBean.setToken(token);
                        Result<UserLoginSuccessBean> result = new Result<>(userLoginSuccessBean);
                        return JSONObject.toJSONString(result);

                        //用户注册成功，token插入失败，让用户登录
                    } else {
                        EmptyBean emptyBean = new EmptyBean();
                        Result<EmptyBean> result = new Result<>(emptyBean, ErrorCodeEnum.FAIL, "登录失败");
                        return JSONObject.toJSONString(result);
                    }

                } else {
                    EmptyBean emptyBean = new EmptyBean();
                    Result<EmptyBean> result = new Result<>(emptyBean, ErrorCodeEnum.FAIL, "登录失败，未查询到账号");
                    return JSONObject.toJSONString(result);
                }

            } else {
                EmptyBean emptyBean = new EmptyBean();
                Result<EmptyBean> result = new Result<>(emptyBean, ErrorCodeEnum.FAIL, "登录失败，请检查您的密码");
                return JSONObject.toJSONString(result);
            }
        }

    }


    /**
     * 设置、上传用户信息
     */
    @PostMapping("/setUserInfo")
    @ResponseBody
    public String setUserInfo(HttpServletRequest request, @RequestParam(value = "user_name") String user_name) {
        if (StringUtils.isEmpty(user_name)) {
            EmptyBean emptyBean = new EmptyBean();
            Result<EmptyBean> result = new Result<>(emptyBean, ErrorCodeEnum.FAIL, "请上传正确的用户名");
            return JSONObject.toJSONString(result);
        }

        String token = request.getHeader("token");
        int user_id = JWTToken.getUserId(token);
        if (user_id <= 0) {
            EmptyBean emptyBean = new EmptyBean();
            Result<EmptyBean> result = new Result<>(emptyBean, ErrorCodeEnum.FAIL, "未获取到要设置的用户信息");
            return JSONObject.toJSONString(result);
        }

        UserBean userBean = new UserBean();
        userBean.setUser_id(user_id);
        userBean.setUser_name(user_name);
        int userId = userService.updateUserInfo(userBean);

        EmptyBean emptyBean = new EmptyBean();
        Result<EmptyBean> result;
        //更新成功
        if (userId > 0) {
            emptyBean.setMsg("设置成功");
            result = new Result<>(emptyBean);

        } else {
            result = new Result<>(emptyBean, ErrorCodeEnum.FAIL, "用户名设置失败,请重新提交");
            return JSONObject.toJSONString(result);
        }
        return JSONObject.toJSONString(result);
    }


    /**
     * 设置、上传用户信息
     */
    @PostMapping("/getUserInfo")
    @ResponseBody
    public String getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        int user_id = JWTToken.getUserId(token);
        if (user_id <= 0) {
            EmptyBean emptyBean = new EmptyBean();
            Result<EmptyBean> result = new Result<>(emptyBean, ErrorCodeEnum.FAIL, "未获取到要查找的用户信息");
            return JSONObject.toJSONString(result);
        }

        UserBean userBean = userService.getUserInfo(user_id);
        if (userBean != null) {
            UserInfoBean userInfoBean =new UserInfoBean();
            userInfoBean.setUser_name(userBean.getUser_name());
            Result<UserInfoBean> result = new Result<>(userInfoBean);
            return JSONObject.toJSONString(result);
        }

        EmptyBean emptyBean = new EmptyBean();
        Result<EmptyBean> result = new Result<>(emptyBean, ErrorCodeEnum.FAIL, "获取信息失败");
        return JSONObject.toJSONString(result);
    }

}
